package com.jin.webvideo.base.spring.interceptor;

import com.jin.webvideo.base.LoginHandler;
import com.jin.webvideo.service.ShareRoomService;
import com.jin.webvideo.util.base.StringUtil;
import com.jin.webvideo.websocket.shareroom.ShareRoom;
import com.jin.webvideo.websocket.shareroom.ShareRoomManager;
import com.jin.webvideo.websocket.shareroom.entity.RoomUtil;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

public class WebSocketHandshakeInterceptor implements HandshakeInterceptor {
    private ShareRoomService shareRoomService = new ShareRoomService();
    private ShareRoomManager manager;
    public WebSocketHandshakeInterceptor(ShareRoomManager manager) {
        this.manager = manager;
    }
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        ServletServerHttpRequest serverHttpRequest = (ServletServerHttpRequest)request;
        HttpServletRequest serverRequest = serverHttpRequest.getServletRequest();
        HttpSession session = serverRequest.getSession();
        String account = LoginHandler.getAccount(session);
        String token = serverRequest.getParameter("token");
        // 校验token
        Map<String, String> tokenInfo = shareRoomService.checkToken(token);
        if (!checkToken(tokenInfo, account)){
            // 握手失败
            return false;
        }
        // 设置基本信息
        long roomId = Long.valueOf(tokenInfo.get("roomId"));
        attributes.put("roomId", roomId);
        attributes.put("account", account);
        ShareRoom room = manager.findByRoomId(roomId);
        if (null == room){
            return false;
        }
        // 校验房间是否允许加入
        return RoomUtil.checkJoin(room, account);
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
    private boolean checkToken(Map<String, String> tokenInfo, String account2){
        if (tokenInfo == null || account2 == null){
            // 握手失败
            return false;
        }
        String account = tokenInfo.get("account");
        if (StringUtil.isEmpty(account) || !account.equals(account2)){
            return false;
        }
        String roomId = tokenInfo.get("roomId");
        if (!StringUtil.isNumber(roomId)){
            return false;
        }
        return true;
    }
}
